package cn.dataling.dag.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池工具类
 */
public class ThreadPoolUtil {

    private static volatile ExecutorService executorService = null;

    private static volatile ScheduledExecutorService scheduledExecutorService = null;

    /**
     * 获取单例线程池
     *
     * @return 线程池
     */
    public static ExecutorService getExecutorService() {
        if (executorService == null) {
            synchronized (ThreadPoolUtil.class) {
                if (executorService == null) {
                    executorService = new ThreadPoolExecutor(
                            Runtime.getRuntime().availableProcessors() << 2,
                            Runtime.getRuntime().availableProcessors() << 4,
                            60,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(1000),
                            new ThreadPoolExecutor.CallerRunsPolicy()
                    );
                }
            }
        }
        return executorService;
    }

    /**
     * 获取单例的定时任务执行线程池
     * 切记
     * 线程池内部任务必须捕获异常 否则会导致线程池内后续的任务不再执行
     *
     * @return 线程池
     */
    public static ScheduledExecutorService getScheduledExecutorService() {
        if (scheduledExecutorService == null) {
            synchronized (ThreadPoolUtil.class) {
                if (scheduledExecutorService == null) {
                    scheduledExecutorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() << 4);
                }
            }
        }
        return scheduledExecutorService;
    }

}
